package com.example.concurrency.exercise;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: dangwen
 * @createDate: 2021/2/5
 */
public class ConditionDemo {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    void await(){
        lock.lock();
        try {
            condition.await();
            System.out.println("等待完毕.....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void signal(){
        lock.lock();
        try {
            condition.signal();
            System.out.println("唤醒完毕.....");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConditionDemo demo = new ConditionDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始等待.....");
                demo.await();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("准备唤醒.....");
                demo.signal();
            }
        }).start();
    }

}
